package cn.shop.admin.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.shop.admin.req.UpdateBalanceReq;
import cn.shop.admin.service.BackSettingService;
import cn.shop.admin.service.MerchantUserService;
import cn.shop.admin.service.RecordService;
import cn.shop.base.MyPage;
import cn.shop.transcation.backSetting.entity.BackSetting;
import cn.shop.transcation.merchantRateModule.entity.MerchantRate;
import cn.shop.transcation.merchantUser.mapper.entity.AuditAliasReq;
import cn.shop.transcation.merchantUser.mapper.entity.MerchantUser;
import cn.shop.transcation.rechargerecord.entity.Record;
import cn.shop.utils.ApiResult;
import cn.shop.utils.annotation.OperationLog;
import cn.shop.utils.constant.Constant;
import cn.shop.utils.constant.SystemSettingConstant;
import cn.shop.utils.enums.OperationType;
import cn.shop.utils.enums.TransactionState;
import cn.shop.validation.Save;
import cn.shop.validation.Update;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 商户管理
 *
 * @author jzw
 * @since 2021-11-04 17:17:39
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/merchantUser")
public class MerchantUserController {

	/**
	 * 服务对象
	 */
	@Resource
	private MerchantUserService merchantUserService;

	@Resource
	private RecordService recordService;

	@Resource
	private BackSettingService backSettingService;

	/**
	 * 获取商户加密信息
	 *
	 * @param merchantUser 查询实体
	 * @return 所有数据
	 */
	@GetMapping("merchantSystemCode")
	public ApiResult<Map<String, String>> merchantSystemCode(MerchantUser merchantUser) {
		return ApiResult.success(merchantUserService.merchantSystemCode(merchantUser));
	}

	/**
	 * 获取商户的游戏名称
	 *
	 * @param id 商户id
	 * @return 所有数据
	 */
	@GetMapping("getGameName")
	public ApiResult<List<Map<String, String>>> getGameName(Long id) {
		return ApiResult.success(merchantUserService.getGameName(id));
	}

	/**
	 * 获取商户二级域名
	 *
	 * @param id 商户id
	 * @return 所有数据
	 */
	@GetMapping("/alias/{id}")
	public ApiResult<List<Map<String, String>>> getAliasName(@PathVariable Long id) {
		return ApiResult.success(merchantUserService.getAliasName(id));
	}

	/**
	 * 审核二级域名
	 */
	@PutMapping("/alias/audit")
	public ApiResult<Map<String, Object>> auditAlias(@Validated @RequestBody AuditAliasReq auditAliasReq) {
		return ApiResult.result(merchantUserService.auditAlias(auditAliasReq.getId(), auditAliasReq.getState()));
	}

	/**
	 * 分页查询所有数据
	 *
	 * @param page         分页对象
	 * @param merchantUser 查询实体
	 * @return 所有数据
	 */
	@GetMapping("queryByPage")
	public ApiResult<MyPage<MerchantUser>> queryByPage(MyPage<MerchantUser> page, MerchantUser merchantUser,
	                                                   @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime startTime,
	                                                   @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime endTime) {
		QueryWrapper<MerchantUser> wrapper = Wrappers.query();
		wrapper.eq("uid", 0L).setEntity(merchantUser)
				.apply(startTime != null,
						"date_format (create_time,'%Y-%m-%d %H:%i') >= date_format ({0},'%Y-%m-%d %H:%i')", startTime)
				.apply(endTime != null,
						"date_format (create_time,'%Y-%m-%d %H:%i') <= date_format ({0},'%Y-%m-%d %H:%i')", endTime)
				.select("account", "balance", "gender", "INSERT( identity_card,4,11,'***********' ) identity_card", "id", "name", "phone", "publicity", "state");
		return ApiResult.success(merchantUserService.page(page, wrapper));
	}

	/**
	 * 通过主键查询单条数据
	 *
	 * @param id 主键
	 * @return 单条数据
	 */
	@GetMapping("queryOne/{id}")
	public ApiResult<MerchantUser> selectOne(@PathVariable Serializable id) {
		return ApiResult.success(merchantUserService.getById(id));
	}

	/**
	 * 注册
	 *
	 * @param merchantUser 实体对象
	 * @return 新增结果
	 */
	@PostMapping("register")
	public ApiResult<Map<String, Object>> register(@Validated @RequestBody MerchantUser merchantUser) {
		merchantUser.setState(1);
		merchantUser.setAgentId(null);
		return ApiResult.result(merchantUserService.register(merchantUser));
	}

	/**
	 * 新增数据
	 *
	 * @param merchantUser 实体对象
	 * @return 新增结果
	 */
	@PostMapping("insert")
	@OperationLog(desc = "新增商户", type = OperationType.CREATE)
	public ApiResult<Map<String, Object>> insert(@Validated(Save.class) @RequestBody MerchantUser merchantUser) {
		merchantUser.setState(2);
		// 商户默认商品公示期为15天
		merchantUser.setPublicity(15);
		return ApiResult.result(merchantUserService.register(merchantUser));
	}

	/**
	 * 修改数据
	 *
	 * @param merchantUser 实体对象
	 * @return 修改结果
	 */
	@PutMapping("setPublicity")
	@OperationLog(desc = "修改商户", type = OperationType.UPDATE)
	public ApiResult<Map<String, Object>> setPublicity(@RequestBody MerchantUser merchantUser) {
		LambdaUpdateWrapper<MerchantUser> updateWrapper = Wrappers.lambdaUpdate();
		updateWrapper.set(MerchantUser::getPublicity, merchantUser.getPublicity()).eq(MerchantUser::getId, merchantUser.getId());
		return ApiResult.result(merchantUserService.update(updateWrapper));
	}

	/**
	 * 修改数据
	 *
	 * @param merchantUser 实体对象
	 * @return 修改结果
	 */
	@PutMapping("update")
	@OperationLog(desc = "修改商户", type = OperationType.UPDATE)
	public ApiResult<Map<String, Object>> update(@Validated(Update.class) @RequestBody MerchantUser merchantUser) {
		return ApiResult.result(merchantUserService.update(merchantUser));
	}

	/**
	 * 修改费率数据
	 *
	 * @return 修改结果
	 */
	@PutMapping("updateRate")
	@OperationLog(desc = "修改商户", type = OperationType.UPDATE)
	public ApiResult<Map<String, Object>> updateRate(@RequestBody MerchantRate merchantRate) {
		return ApiResult.result(merchantUserService.updateRate(merchantRate));
	}

	/**
	 * 审核
	 *
	 * @param merchantUser 实体对象
	 * @return 修改结果
	 */
	@PutMapping("audit")
	public ApiResult<Map<String, Object>> audit(@Validated(Update.class) @RequestBody MerchantUser merchantUser) {
		// Assert.notNull(merchantUser.getServiceRate(), "服务费率不能为空");
		merchantUser.setState(2);
		return ApiResult.result(merchantUserService.audit(merchantUser));
	}

	/**
	 * 给玩家充值 总管理员才能充值
	 *
	 * @return 所有数据
	 * @author jzw
	 * @since 2022-02-23 09:39:05
	 */
	@PutMapping("setBalance")
	@SaCheckRole("ROOTUSER")
	public ApiResult<Map<String, Object>> update(@RequestBody UpdateBalanceReq updateBalanceReq) {
		BackSetting backSetting = backSettingService.getOneByKey(SystemSettingConstant.ADMIN_TRANSACTION_PASSWORD);
		if (StrUtil.isBlank(backSetting.getValue())) {
			return ApiResult.fail("请设置交易密码");
		}
		if (!DigestUtil.bcryptCheck(updateBalanceReq.getPassword(), backSetting.getValue())) {
			return ApiResult.fail("交易密码不正确");
		}
		LambdaUpdateWrapper<MerchantUser> updateWrapper = Wrappers.lambdaUpdate();
		MerchantUser merchantUser = merchantUserService.getById(updateBalanceReq.getId());
		updateWrapper.eq(MerchantUser::getId, updateBalanceReq.getId()).setSql("balance = balance + " + updateBalanceReq.getBalance());
		boolean isSuccess = merchantUserService.update(updateWrapper);
		if (isSuccess) {
			Record record = new Record();
			record.setAmount(updateBalanceReq.getBalance());
			record.setActualAmount(record.getAmount());
			record.setBalance(merchantUser.getBalance().add(updateBalanceReq.getBalance()));
			record.setChannel("手动充值");
			record.setChannelId(0L);
			record.setPlayerId(merchantUser.getId());
			record.setPlayerName(merchantUser.getAccount());
			record.setState(TransactionState.MANUAL);
			record.setType(1);
			boolean s = recordService.save(record);
			if (!s) {
				log.info("手动充值记录保存失败 {}", record);
			}
		}
		return ApiResult.result(isSuccess);
	}

	/**
	 * 获取商户信息
	 *
	 * @param id 编号
	 * @return 返回结果
	 */
	@GetMapping("/info/{id}")
	public ApiResult<MerchantUser> info(@PathVariable long id) {
		return ApiResult.success(merchantUserService.getById(id));
	}

	/**
	 * 删除单条数据
	 *
	 * @param id 主键
	 * @return 删除结果
	 */
	@DeleteMapping("delete/{id}")
	public ApiResult<Map<String, Object>> delete(@PathVariable Long id, String password) {
		BackSetting backSetting = backSettingService.getOneByKey(SystemSettingConstant.ADMIN_TRANSACTION_PASSWORD);
		if (StrUtil.isBlank(backSetting.getValue())) {
			return ApiResult.fail("请设置交易密码");
		}
		if (!DigestUtil.bcryptCheck(password, backSetting.getValue())) {
			return ApiResult.fail("交易密码不正确");
		}
		MerchantUser merchantUser = new MerchantUser();
		merchantUser.setId(id);
		return ApiResult.result(merchantUserService.removeById(merchantUser));
	}

	/**
	 * 批量删除数据
	 *
	 * @param idList 主键结合
	 * @return 删除结果
	 */
	@DeleteMapping("batchDelete")
	public ApiResult<Map<String, Object>> batchDelete(@RequestParam("idList") List<Long> idList) {
		return ApiResult.result(merchantUserService.batchDelete(idList, new MerchantUser()));
	}

}

